/**
 * 项目打包步骤
 * 1. 运行yarn generate同步prisma命令
 * 2. 删除build目录
 * 3. 运行yarn ncc打包命令
 * 4. 将/build/client下面的文件移动到/build/下
 * 5. 删除多余的/build/client文件夹
 * 6. 复制文件夹.env .fcignore到/build/下
 */
import * as path from 'path';
import * as fs from 'fs';
import * as child_process from 'child_process';
import * as fse from 'fs-extra';

/**
 * 编译配置
 */
const Config = {
  /** 编译后文件夹相对路径，相对于根项目 */
  targetDir: './build',
  /** 复制文件 */
  copyFile: [
    { from: './build/client/libquery_engine-debian-openssl-1.0.x.so.node', to: './build/libquery_engine-debian-openssl-1.0.x.so.node' },
    { from: '.env', to: './build/.env' },
    { from: '.fcignore', to: './build/.fcignore' },
  ],
  /** 用软链接代替文件夹复制 */
  copyDir: [
    { from: './public', to: './build/public' },
  ],
}

/** 
 * 清空输出目录
 */
function clearDir(dir: string) {
  if (fs.existsSync(dir)) {
    fs.rmSync(dir, { recursive: true });
  }
}

/**
 * 复制文件
 */
function copyFile(sourceFilePath: string, targetFilePath: string) {
  if (fs.existsSync(targetFilePath)) {
    fs.rmSync(targetFilePath, { recursive: true });
  }
  fs.copyFileSync(sourceFilePath, targetFilePath);
}

/**
 * 删除目录
 */
function deletePath(path: string) {
  if (fs.existsSync(path)) {
    fs.rmSync(path, { recursive: true });
  }
}

/**
 * 移动目录下所有文件
 */
function moveFolders(sourceDir: string, targetDir: string) {
  // 获取源目录中的所有文件和子目录
  const files = fs.readdirSync(sourceDir);

  // 遍历所有文件和子目录
  for (const file of files) {
    const filePath = path.join(sourceDir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      // 如果是目录，则递归调用 moveFolders() 处理子目录
      moveFolders(filePath, targetDir);
    } else {
      // 如果是文件夹，则将其移动到目标目录下
      const targetPath = path.join(targetDir, file);
      fs.renameSync(filePath, targetPath);
    }
  }
}

function main() {
  console.log('>>> 打包中...')
  child_process.execSync('yarn generate');
  clearDir(path.join(process.cwd(), Config.targetDir));
  child_process.execSync('yarn ncc');
  // moveFolders(
  //   path.join(process.cwd(), Config.targetDir, './client'),
  //   path.join(process.cwd(), Config.targetDir)
  // );
  Config.copyFile.forEach(item => {
    copyFile(item.from, path.join(process.cwd(), item.to));
  })
  Config.copyDir.forEach(item => {
    fse.copySync(item.from, item.to);
  })
  deletePath(path.join(process.cwd(), Config.targetDir, 'client'));
  console.log('>>> 打包成功...')
}

main();